package com.itheima.springbootwebtlias.interceptor;

import com.itheima.springbootwebtlias.util.CurrentHolder;
import com.itheima.springbootwebtlias.util.JwtUtils;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


@Slf4j
@Component
public class TokenInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String url = request.getRequestURI().toString();

        //2.判断请求路径是否为登录请求
        //如果为登录请求，直接放行
        if (url.contains("/login")) {
            log.info("登录请求，直接放行");
            return true;
        }


        //3.获取请求头中的令牌
        String jwt = request.getHeader("token");
        if (jwt == null) {
            log.info("请求头中没有令牌,请登录... ...");
            //没有携带令牌，封装错误结果
            response.setStatus(HttpStatus.SC_UNAUTHORIZED); //401
            //response.setStatus(401);
            return false;
        }

        //4.解析令牌，判断令牌是否正确
        try {
            JwtUtils.parseJWT(jwt);  //依靠工具类解析令牌
        } catch (Exception e) {
            log.info("令牌解析错误，请重新登录... ...");
            //解析错误，封装错误结果
            response.setStatus(HttpStatus.SC_UNAUTHORIZED); //401
            return false;
        }

        //5.放行
        log.info("令牌解析正确，放行... ...");

        //从请求头中获取当前登录的员工令牌，解析令牌，获取当前登录用户的ID
        String token = request.getHeader("token"); //  获取令牌
        Claims claims = JwtUtils.parseJWT(token); // 解析令牌
        Integer id = (Integer) claims.get("id"); //  获取当前登录用户的ID

        CurrentHolder.setCurrentId(id);//存储当前登录用户的ID
        return true;
    }
}
